import React from 'react'
import { Form } from 'semantic-ui-react'
// 导入样式
import './Login.css'

import axios from 'axios'

class Login extends React.Component {
  constructor() {
    super()

    this.state = {
      uname: '',
      pwd: ''
    }
  }

  // 登录
  login = () => {
    axios
      .post(`users/login`, {
        uname: this.state.uname,
        pwd: this.state.pwd
      })
      .then(res => {
        // console.log(res)
        if (res.meta.status === 200) {
          // 保存token到本地
          localStorage.setItem('mytoken', res.data.token)

          // 设置用户id
          localStorage.setItem('uid',res.data.uid)

          const { history } = this.props

          // 跳转到首页
          history.push('/main')
        }
      })
  }

  /**
  changeUname = e => {
    this.setState({
      uname: e.target.value
    })
  }

  changePwd = e => {
    this.setState({
      pwd: e.target.value
    })
  }
  */

  // 这句相当于上面两句
  changeValue = ({ target }) => {
    // console.log(target)
    this.setState({
      [target.name]: target.value
    })
  }

  render() {
    return (
      <div className="login-container">
        <div className="login-title">登录</div>
        <div className="login-form">
          <Form onSubmit={this.login}>
            <Form.Input
              required
              icon="user"
              size="big"
              name="uname"
              iconPosition="left"
              value={this.state.uname}
              onChange={this.changeValue}
              placeholder="请输入用户名"
            />
            <Form.Input
              required
              type="password"
              icon="lock"
              size="big"
              name="pwd"
              iconPosition="left"
              value={this.state.pwd}
              onChange={this.changeValue}
              placeholder="请输入密码"
            />
            <Form.Button positive content="登录" />
          </Form>
        </div>
      </div>
    )
  }
}

export default Login
